/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-05-08 15:55:05
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-05-14 16:53:17
 * @FilePath: /data-center-web-update/src/utils/array.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
export interface TreeData<T> {
    children?: T[];
}
export type TreeDataWithParent<T extends TreeData<T>> = T & { parent?: T };
export const treeToArray = <T extends TreeData<T>>(
    tree: T[],
    parent?: TreeDataWithParent<T>
): TreeDataWithParent<T>[] => {
    let res: TreeDataWithParent<T>[] = [];
    for (const item of tree) {
        const { children, ...rest } = item;
        const newItem = { children, ...rest, parent } as TreeDataWithParent<T>;
        res.push(newItem);
        if (children && children.length > 0) {
            res = [...res, ...treeToArray(children, newItem)];
        }
    }
    return res;
};

export function arrayToTree<T extends TreeData<T>>(
    items: TreeDataWithParent<T>[]
): TreeData<T>[] {
    // 用于构建树的辅助函数
    function buildTree(parent?: T): T[] {
        return items
            .filter((item) => item.parent === parent) // 查找所有子节点
            .map((item) => {
                const children = buildTree(item);
                return {
                    ...item,
                    children: children.length > 0 ? children : undefined, // 递归地构建子树
                    parent: undefined // 在树中不需要父节点引用
                };
            });
        // .filter((item) => item.children.length > 0); // 过滤掉没有子节点且不是根节点的元素（可选）
    }

    // 从没有父节点的元素开始构建树
    return buildTree();
}
